package com.polaris.live.viewmodel.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.AppModule
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.resp.back_resp.IsRegisteredResp
import kotlinx.coroutines.launch

/**
 * 手机号登录的viewModel
 *
 * @author Created by 半仙 on 2023/8/15/015 17:12
 */
class PhoneNumberModel : LoginViewModel() {

    val isRegisteredLiveData = MutableLiveData<ResultState<IsRegisteredResp>>()
    val areaCodeLiveData = MutableLiveData<AreaCodeResp>()

    fun isRegistered(areaCode: String, phoneNumber: String) {
        val uniqueId = AppModule.requireUniqueDeviceId()

        requestLoading(
            { userService.isRegistered(AppConst.APP_TYPE, areaCode, phoneNumber, uniqueId) },
            isRegisteredLiveData
        )
    }

    fun isGmailRegistered(gmail: String) {
        val uniqueId = AppModule.requireUniqueDeviceId()

        requestLoading(
            { userService.isGmailRegistered(AppConst.APP_TYPE, gmail, uniqueId) },
            isRegisteredLiveData, waitTime = 0
        )
    }

    fun getAreaCodeByCountryCode(countryCode: String) {
        viewModelScope.launch {
            val list = AssetsConfigManager.fetchAreaCodeAndSave()

            //真找不到也没办法，理论上不可能
            list.find { it.countryCode == countryCode }?.also {
                areaCodeLiveData.value = it
            }
        }
    }

    fun getCountryCodeByAreaCode(areaCode: String) {
        viewModelScope.launch {
            val list = AssetsConfigManager.fetchAreaCodes()

            //真找不到也没办法，理论上不可能
            list.find { it.areaCode == areaCode }?.also {
                areaCodeLiveData.value = it
            }
        }
    }
}